package com.stream.utils;

import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.DuplicateFormatFlagsException;

/**
 * Created by yebaokang on 2017/5/18.
 */
public class RRExceptionHandler implements HandlerExceptionResolver {
    private static final Logger logger = LoggerFactory.getLogger(RRExceptionHandler.class);


    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {

        try {
            R r = new R();
            httpServletResponse.setContentType("application/json;charaset=utf-8");
            httpServletResponse.setCharacterEncoding("utf-8");
            if (e instanceof RRException) {
                RRException rr = (RRException) e;
                r.put("code", rr.getCode());
                r.put("msg", rr.getMsg());
            } else if (e instanceof DuplicateFormatFlagsException) {
                r = R.error("数据库中已存在该记录");
            } else if (e instanceof AuthorizationException) {
                r = R.error("该用户无此权限");
            } else {
                r = R.error();
            }
            //记录异常日志
            logger.error(e.getMessage(), e);

            String msg = JSON.toJSONString(e);
            httpServletResponse.getWriter().print(msg);
        } catch (IOException e1) {
            logger.error("RRExceptionHandler 异常处理失败：", e);
        }

        return new ModelAndView();
    }
}
